package com.lxq.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.lxq.common.DaoFactory;
import com.lxq.dao.UserDao;
import com.lxq.entity.User;
import com.lxq.web.servlet.common.BaseServlet;

@WebServlet("/app/login")
public class LoginServlet extends BaseServlet {

	private static final long serialVersionUID = 1833657034691802184L;
	private UserDao userDao = DaoFactory.getInstance("userDao", UserDao.class);

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String phone = request.getParameter("phone");
		String password = request.getParameter("password");

		
		User user = userDao.findByPhone(phone);
		JSONObject json = new JSONObject();
		try {
			Thread.sleep(1000);
			
			if (user == null) { // 说明用户不存在

				json.put("success", false);

				json.put("reason", "用户未注册");
			} else {
				if (password.equals(user.getPassword())) {
					json.put("success", true);
					JSONObject userJSON = new JSONObject(user);
					json.put("user", userJSON);
					
					request.getSession().setAttribute("curr_user", user);
					
				} else {
					json.put("success", false);
					json.put("reason", "密码不正确");
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json.toString());
		response.getWriter().flush();

	}

}
